package com.dayuanit.mall.bank.task;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dayuanit.mall.bank.dao.SinaOrderDao;
import com.dayuanit.mall.bank.domain.SinaNotifyResponse;
import com.dayuanit.mall.bank.domain.SinaOrder;
import com.dayuanit.mall.bank.notify.SinaNotify;
import com.dayuanit.mall.bank.payenum.NotifyStatusEnum;
import com.dayuanit.mall.bank.payenum.PayOrderEnum;

@Component("sinaNotifyTask")
public class SinaNotifyTask {
	
	private static final Logger log = LoggerFactory.getLogger(SinaNotifyTask.class);
	
	@Autowired
	private SinaOrderDao sinaOrderDao;
	
	@Autowired
	private SinaNotify sinaNotify;
	
	private static final int PRE_NUM = 2;
	private static final int NOTIFY_MAX_TIMES = 10;
	
	public void doTask() {
		log.info("新浪异步通知正在进行...");
		int off = 0;
		List<SinaOrder> sinaOrderList = null;
		
		do {
			sinaOrderList = sinaOrderDao.listSinaOrders4Notify(PayOrderEnum.ALREADY_PAID.getStatus(), NotifyStatusEnum.未通知.getStatus(), PRE_NUM, off, NOTIFY_MAX_TIMES);
			for (SinaOrder so : sinaOrderList) {
				notifyMerchant(so);
			}
			
			off += PRE_NUM;
			
		} while (null != sinaOrderList && sinaOrderList.size() > 0);
		
		log.info("新浪异步通知结束...");
	}
	
	private void notifyMerchant(SinaOrder so) {
		log.info("订单{}正在通知商户,地址：{}", so.getOrderId(), so.getSynchMerchantUrl());
		SinaNotifyResponse snr = sinaNotify.sendNotify(so);
		// 修改订单通知状态为已通知
		if (snr.processSuccess()) {
			sinaOrderDao.updateNotifyStatus(so.getId(), so.getNotifyStatus(), NotifyStatusEnum.已通知.getStatus());
		}
	}
	
}
